package com.wpp.algorithm.lagou.part1.lesson5;

import com.wpp.data_structure.MyNode;

/**
 * @author wpp25
 * @date 2021/6/9 20:42
 * @description：
 */
public class Lesson5 {

    // 给定一个链表 判断链表中是否有环  存在返回true，否则 返回 false

    /**
     *   str0 ->  str1 ->  str2 -> str3 -> str1 有环
     * @param args
     */
    public static void main(String[] args) {
        MyNode<String> node = new MyNode<>("str0");
        MyNode<String> curr = node;
        for (int i = 1; i < 4; i++) {
            MyNode<String> node1 = new MyNode<>("str" + i);
            curr.next = node1;
            curr = node1;
            if (i == 3) {
                node1.next = node.next;
            }
        }
        System.out.println(hasCycle(node));
    }

    //
    private static boolean hasCycle(MyNode<String> node)  {
        if (node == null) {
            return false;
        }
        MyNode<String> slowNode = node;
        MyNode<String> fastNode  = node.next;

        while (fastNode != null && fastNode.next != null) {
            if (fastNode == slowNode) {
                return true;
            }
            fastNode = fastNode.next.next;
            slowNode = slowNode.next;
        }
        return false;
    }
}
